﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using RTGather.Lib.gather;
using QQ.Util;
using RTGather.Lib;
using RuoTeng.Util;
using System.Data.OleDb;
using System.Web;
using System.Threading;

namespace RTGather
{
    public partial class ClickBank : Form
    {

        public string keyword = "";

        public int count = 0;

        public fbb_ClickBank amazon1 = null;

        public Thread sendThread = null;

        public Thread gatherThread = null;



        public GatherClickBank gatherProduct = null;
        private static string rootpath = Application.StartupPath;//根目录
        private string datapath = rootpath + "\\Data";
        
        private string oldsend = rootpath + "\\已发布产品.txt";
        public ClickBank()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; 
            InitializeComponent();
            amazon1 = new fbb_ClickBank(); 
           
        }
        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_search_Click(object sender, EventArgs e)
        {
            search();
        }



        /// <summary>
        /// 判断是否重复
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsRepeat(string url,string filename)
        {
            List<string> list = TextBoxTools.getFileList(filename);
            bool isrepeat = list.Contains(url);
            return isrepeat;
        }


        /// <summary>
        /// 搜索按钮
        /// </summary>
        private void search()
        {
            keyword = txt_keyword.Text.Trim();
            if (keyword != "")
            {
            
                count = amazon1.getCount(keyword);
                lb_result.Text = string.Format("搜索结果：共计收到{0}条产品信息", count);
                if (count > 0)
                {
                    btn_gather.Enabled = true;
                }
                else
                {
                    btn_gather.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show("请输入关键词");
            }
        }
        /// <summary>
        /// 采集按钮
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_gather_Click(object sender, EventArgs e)
        {

            if (btn_gather.Text =="采集")
            {
                ///========数据验证==============  
                if (txt_vcode.Text != "" && count != 0 && keyword != "")
                {

                    ConfigXML.VCode = txt_vcode.Text;
                    startGather();
                }
                else
                {
                    MessageBox.Show("非法操作！请检查操作流程");
                }
            }
            else
            {
                gatherThread.Abort();
                MessageBox.Show("采集进程被打断了！");
                btn_gather.Text = "采集";
                btn_search.Enabled = true;

            }

        }

        private void Yahoo_Load(object sender, EventArgs e)
        {
            txt_vcode.Text = ConfigXML.VCode;
            txt_sendUrl.Text = ConfigXML.SendUrl;
            RTFile.creatDir(".\\Data");//用于存放数据的目录
            
        }


        private void startGather()
        { 
            gatherProduct = new GatherClickBank();

            gatherProduct.amazon = amazon1;

            gatherProduct.vcode = txt_vcode.Text;
            gatherProduct.keyword = keyword;
           
            gatherProduct.count = count;
            gatherProduct.filename = rootpath+"\\Data\\"+keyword+".xls";
            gatherProduct.Log += new GatherClickBank.LogHandle(this.Log);
            gatherProduct.ShowStop += new RuoTeng.Util.Task.TaskEventHandler(this.ShowStop);
            gatherThread = new Thread(gatherProduct.Start);
            gatherThread.IsBackground = true;
            gatherThread.Name = "采集进程";
            gatherThread.Start();

            btn_gather.Text = "停止";
            btn_search.Enabled = false;
            txt_log.Text = "";
            
        }



        private void Log(string log, System.Drawing.Color color)
        {
            txt_log.AppendText(log+System.Environment.NewLine);
            txt_log.ForeColor = color;
        }

        /// <summary>
        /// 写入新的记录
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="filename"></param>
        private void writeNew(string pid,string filename)
        {
            string old = RTFile.ReadFile(filename);
            string newstring = old + pid + System.Environment.NewLine;
            RTFile.WriteFile(filename, newstring);

        }

        private void ShowStop(RuoTeng.Util.Task work)
        {
            btn_search.Enabled = true;
            btn_gather.Text = "采集";
        }
        /// <summary>
        /// 发布数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_sendData_Click(object sender, EventArgs e)
        {

            if (btn_sendData.Text == "开始发布")
            {
                string sendurl = txt_sendUrl.Text.Trim();
                if (sendurl != "")
                {
                    if (data_send.Rows.Count > 0)
                    {
                        txt_sendLog.Text = "";
                        ConfigXML.SendUrl = txt_sendUrl.Text;
                        btn_sendData.Text = "停止";
                        sendThread = new Thread(ReadData);
                        sendThread.IsBackground = true;
                        sendThread.Name = "发布消息";
                        sendThread.Start();   
                    }
                    else
                    {
                        MessageBox.Show("发布数据不能为空哦！请导入数据再发布");
                    }

                }
                else
                {
                    MessageBox.Show("发布地址不能为空");
                }
            }

            else
            {
                try
                {
                    sendThread.Abort();
                    btn_sendData.Text = "开始发布";
                }
                catch { }

            }

        }


        /// <summary>
        /// 获取数据
        /// </summary>
        private void ReadData()
        {
            CallMessage("发布开始");
            try
            {
                for (int j = 0; j < this.data_send.Rows.Count; j++)
                {

                    string Pid = data_send.Rows[j].Cells[0].Value.ToString();
                    CallMessage("开始发布产品ID：" + Pid);
                    string pname = data_send.Rows[j].Cells[1].Value.ToString();
                    pname = HttpUtility.UrlEncode(pname);

                    string pdesc = data_send.Rows[j].Cells[2].Value.ToString() + "<br>" + data_send.Rows[j].Cells[3].Value.ToString(); 

                   pdesc = HttpUtility.UrlEncode(pdesc);

                    if (IsRepeat(Pid, oldsend) == false)///判断是否重复！不重复即发布！并记录pid
                    {
                        bool succ = sendContent(pname, pdesc);
                        if (succ == true)
                        {
                            writeNew(Pid, oldsend);
                            CallMessage("产品ID:" + Pid + "发布成功");
                        }
                        else
                        {
                            CallMessage("产品ID:" + Pid + "发布失败");
                        }

                    }
                    else
                    {
                        CallMessage("产品ID重复！自动跳过！");
                    }
                }
            }
            catch { }

            CallMessage("发布完成");
            MessageBox.Show("发布完成");

            btn_sendData.Text = "开始发布";

        }


        private void CallMessage(string log)
        {
            txt_sendLog.AppendText(log+System.Environment.NewLine);
        }

        /// <summary>
        /// 发布数据到WordPress
        /// </summary>
        /// <param name="pName"></param>
        /// <param name="Pdesc"></param>
        /// <param name="Pcode"></param>
        private bool sendContent(string pName, string Pdesc)
        {

            bool state = false;
            try
            {

                string url = string.Format("{0}/rt.php?action=save", txt_sendUrl.Text);
                string postDate = string.Format("post_title={0}&post_category=1&post_date=&tag={1}&post_content={2}", pName, pName, Pdesc);
                string result = Http.GetData(url, postDate, null, Encoding.UTF8);

                if (result.Contains("sendsucc") == true)
                {

                     state=true;
                }
                else
                {
                    state= false;
                }
            }

                
            catch { }
            return state;
        }





        private DataSet importExcelToDataSet(string FilePath)
        {
            string strConn;

            //strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties='Excel 12.0;HDR=false;IMEX=1'";
          //  strConn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + FilePath + ";Extended Properties='Excel 8.0;HDR=false;IMEX=1'";
            strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties='Excel 12.0;HDR=false;IMEX=1'";
         
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [sheet1$]", strConn);
            DataSet myDataSet = new DataSet();
            try
            {
                myCommand.Fill(myDataSet);
            }
            catch (Exception ex)
            {
                throw new Exception("该Excel文件的工作表的名字不正确," + ex.Message);
            }
            finally
            {
                conn.Close();
                 
            }
            return myDataSet;
        }
 
         
 
        /// <summary>
        /// 选择文件
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_chooseFile_Click(object sender, EventArgs e)
        {

            if (data_send.Rows.Count > 0)
            {

                DataTable dt = (DataTable)data_send.DataSource;
                dt.Rows.Clear();
                data_send.DataSource = dt;
            }

            OpenFileDialog fileDialog = new OpenFileDialog();
            string path = rootpath + "\\Data\\";
            fileDialog.InitialDirectory = path;
            fileDialog.Title = "请选择excel文件";
            fileDialog.Filter = "WordPress数据发布 (*.xls)|*.xls";
            fileDialog.FilterIndex = 1;
            fileDialog.RestoreDirectory = true;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
              
                String fileName = fileDialog.FileName;
                DataSet ds = importExcelToDataSet(fileName);
                data_send.DataSource = ds.Tables[0];
            }

        }


    }
}
